package com.roocon.thread.daemon;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Program {

  private static int queueCapacity = 10;
  private static BlockingQueue<String> logQueue = new ArrayBlockingQueue<String>(queueCapacity);

  public static void main(String[] args) throws IOException {

    LogWriter writer = new LogWriter();
    LogCleaner cleaner = new LogCleaner();
    cleaner.setDaemon(true);

    writer.start();
    cleaner.start();
  }

  /**
   * 模拟不停写日志（直到队列写满）
   */
  private static class LogWriter extends Thread {
    public void run() {
      for (int i = 0; i < queueCapacity; i++) {
        try {
          logQueue.put("" + i);
          System.out.println("Write log:" + logQueue);
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 模拟在空闲时清理日志（仅保留5条日志）
   */
  private static class LogCleaner extends Thread {
    public void run() {
      while (true) {
        if (logQueue.size() > 5) {
          try {
            System.out.println("Clean up log .. " + logQueue.take());
            Thread.sleep(500);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
}